package com.youxin.logprocess.controller;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.Set;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.apache.log4j.Logger;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import com.youxin.busfoundation.config.MonitorBaseBean;
import com.youxin.busfoundation.config.MonitorMysqlConfig;
import com.youxin.busfoundation.config.MonitorRedisConfig;
import com.youxin.busfoundation.config.MonitorRedisItem;
import com.youxin.foundation.db.redis.RedisClusterBean;
import com.youxin.foundation.db.redis.RedisClusterCommand;
import com.youxin.foundation.lang.BaseException;
import com.youxin.foundation.utils.HostUtils;
import com.youxin.foundation.utils.thread.ScheduleThreadPool;
import com.youxin.logprocess.bean.MessageBean;

import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;

/**
 * Redis服务器监控
 * 
 * @author yingde.cao
 *
 */
public class MonitorRedisController extends BaseMonitorController{
	private MonitorRedisConfig config;

	public MonitorRedisConfig getConfig() {
		return config;
	}

	public void setConfig(MonitorRedisConfig config) {
		this.config = config;
	}

	private static MonitorRedisController controller = new MonitorRedisController();

	public static void initConfig(MonitorRedisConfig config) {
		controller.setConfig(config);
	}

	public static MonitorRedisController instance() {
		return controller;
	}
	
	@Override
	public MonitorBaseBean getMonitorBean() {
		return config;
	}

	/**
	 * 执行方法
	 */
	public void execute() {
		if (config == null) {
			throw new BaseException("请配置"+getMonitorBean().getId()+"的config");
		}
		if (config.getMonitor() != 1) {
			return;
		}
		for (MonitorRedisItem item : config.getHostslist()) {
			ScheduleThreadPool.scheduleWithFixedDelay(new Runnable() {
				@Override
				public void run() {
					try {
						queryStatus(item);
					} catch (Exception e) {
						logger.error("执行任务异常:", e);
						add(item.getHosts().split(",", 0),e);
					}
				}
			}, config.getInterval(), 1000);
		}
	}
	
	/**
	 * redis状况
	 * @param item  redis主机信息
	 * @throws ParseException 解析异常
	 */
	private void queryStatus(MonitorRedisItem item) throws ParseException {
		String[] hosts=item.getHosts().split(",",0);
		for (String host : hosts) {
			Jedis jedis = null;
			try {
				HostAndPort hostPort=HostUtils.parserHost(host);
				jedis = new Jedis(hostPort.getHost(), hostPort.getPort());
				jedis.ping();
			} catch (Exception e) {
				logger.error("连接redis主机" + host + "发生异常", e);
				add(host,e);
			} finally {
				try {
					if (jedis != null) {
						jedis.close();
					}
				} catch (Exception e) {
					logger.error("jedis.close()发生异常", e);
				}
			}
		}

	}

}
